import React, { useState } from 'react';
import { useAppDispatch, useAppSelector } from '../redux/hooks';
import { addTodo, deleteTodo, toggleTodo, updateTodo } from '../redux/todos/todosSlice';
import type { Todo } from '../redux/todos/types';

const TodoList: React.FC = () => {
  const [inputText, setInputText] = useState('');
  const [editingTodo, setEditingTodo] = useState<string | null>(null);
  const [editingText, setEditingText] = useState('');
  
  const dispatch = useAppDispatch();
  const todos = useAppSelector((state) => state.todos.todos);

  // 处理添加Todo
  const handleAddTodo = () => {
    if (inputText.trim()) {
      dispatch(addTodo({ text: inputText.trim() }));
      setInputText('');
    }
  };

  // 处理删除Todo
  const handleDeleteTodo = (id: string) => {
    dispatch(deleteTodo({ id }));
    if (editingTodo === id) {
      setEditingTodo(null);
      setEditingText('');
    }
  };

  // 处理切换Todo完成状态
  const handleToggleTodo = (id: string) => {
    dispatch(toggleTodo({ id }));
  };

  // 开始编辑Todo
  const handleStartEdit = (todo: Todo) => {
    setEditingTodo(todo.id);
    setEditingText(todo.text);
  };

  // 保存编辑的Todo
  const handleSaveEdit = (id: string) => {
    if (editingText.trim()) {
      dispatch(updateTodo({ id, text: editingText.trim() }));
      setEditingTodo(null);
      setEditingText('');
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingTodo(null);
    setEditingText('');
  };

  return (
    <div className="todo-list">
      <h2>待办事项列表</h2>
      
      {/* 添加Todo输入框 */}
      <div className="todo-input-container">
        <input
          type="text"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="添加新的待办事项..."
          onKeyPress={(e) => e.key === 'Enter' && handleAddTodo()}
        />
        <button onClick={handleAddTodo}>添加</button>
      </div>

      {/* Todo列表 */}
      <ul className="todo-items">
        {todos.length === 0 ? (
          <li className="empty-message">暂无待办事项，添加一个吧！</li>
        ) : (
          todos.map((todo) => (
            <li key={todo.id} className={`todo-item ${todo.completed ? 'completed' : ''}`}>
              {editingTodo === todo.id ? (
                // 编辑模式
                <div className="todo-edit">
                  <input
                    type="text"
                    value={editingText}
                    onChange={(e) => setEditingText(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSaveEdit(todo.id)}
                    autoFocus
                  />
                  <div className="edit-buttons">
                    <button onClick={() => handleSaveEdit(todo.id)}>保存</button>
                    <button onClick={handleCancelEdit}>取消</button>
                  </div>
                </div>
              ) : (
                // 显示模式
                <div className="todo-content">
                  <input
                    type="checkbox"
                    checked={todo.completed}
                    onChange={() => handleToggleTodo(todo.id)}
                  />
                  <span className="todo-text">{todo.text}</span>
                  <div className="todo-actions">
                    <button onClick={() => handleStartEdit(todo)}>编辑</button>
                    <button onClick={() => handleDeleteTodo(todo.id)}>删除</button>
                  </div>
                </div>
              )}
            </li>
          ))
        )}
      </ul>

      {/* 统计信息 */}
      <div className="todo-stats">
        总任务数: {todos.length} | 
        已完成: {todos.filter(todo => todo.completed).length} | 
        未完成: {todos.filter(todo => !todo.completed).length}
      </div>
    </div>
  );
};

export default TodoList;